To begin create an asp.net mvc project called mvc-tutorials and also create a class and name it as picture with a single propery file with datatype HttpPostedFileBase.
Step 1: Create a class and give a name picture.Copy and paste the following code.
public class picture {
public HttpPostedFileBase file { get; set; }
}
Step 2: Right click on the "Controllers" folder and add "fileUpload" controller. Copy and paste the following code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVC_tutorials.Controllers
{
public class fileUploadController : Controller
{
//
// GET: /fileUpload/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(picturepicture)
{
if (picture.file.ContentLength > 0) {
var fileName = Path.GetFileName(picture.file.FileName);
var filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
picture.file.SaveAs(filePath);
}
return RedirectToAction("Index");
}
}
}
Step 3: Right click on the "Index" action method in the "fileUploaderController" and add "Index" view. Copy and paste the following code.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>single fileupload in asp.net MVC</title>
<style type="text/css">
.btn {
width: 100px;
height: 50px;
background: #00BCD4;
border-style: solid;
border-color: white;
color: white;
}
</style>
</head>
<body style="border: 1px solid #DED8D8; width: 400px; font-family: Arial; margin-left: 50px">
@using (@Html.BeginForm(null, null, FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td style="padding-bottom: 35px" colspan="2">
<h2 style="color: #FF5722">single file upload in asp.net</h2>
</td>
</tr>
<tr>
<td style="width: 100px;">
<b style="color: #FF5722">File:</b>
</td>
<td>
<input type="file" name="file" id="file" />
</td>
</tr>
<tr>
<td> </td>
<td colspan="2" style="padding-top: 30px">
<input type="submit" class="btn" name="submit" />
</td>
</tr>
</table>
}
</body>
</html>
Output:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article